Genric Methods
(Tap the post to see more)
Generic allows us to write a method that can work with different types while providing compile time safely.
Example program:
package com.Genric;
public class GenericMethods {
// Generic method example
public <T> void printArray(T[] array) {
for (T element : array) {
System.out.print(element + " ");
}
System.out.println();
}
public static void main(String[] args) {
// Example usage of the generic method
Integer[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = {"one", "two", "three", "four", "five"};
GenericMethods genericMethods = new GenericMethods();
genericMethods.printArray(intArray);
genericMethods.printArray(stringArray);
}
}
Comments